// app.js
App({
  d: {
    hostUrl: 'https://tanghuzhao.cn',
    // hostUrl: 'http://www.xshoph.com/index.php',
    hostImg: 'https://tanghuzhao.cn',
    hostVideo: 'http://zhubaotong-file.oss-cn-beijing.aliyuncs.com',
    userId: 0,
    store_Id:0,
    store_sub_Id:0,
    appId: "",
    appKey: "",
    // ceshiUrl: 'http://www.xshoph.com/index.php',
    ceshiUrl: 'https://tanghuzhao.cn',
  },
  position: function () {
    var that = this
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        that.globalData.latitude = res.latitude,
        that.globalData.longitude = res.longitude
      }
    })
  },
  uploadimg: function (data) {
      var that = this,
      i = data.i ? data.i : 0,//当前上传的哪张图片
      success = data.success ? data.success : 0,//上传成功的个数
      fail = data.fail ? data.fail : 0;//上传失败的个数
    wx.uploadFile({
      url: data.url,
      filePath: data.path[i],
      name: 'file',//这里根据自己的实际情况改
      formData: {
        code_one: data.data.code_one,
        code: data.data.code,
        self_name: data.data.self_name,
        card_id: data.data.card_id,
        tel_id: data.data.tel_id,
        user: data.data.user,
        pwd: data.data.pwd,
        city: data.data.city,
        quyu:data.data.quyu,
        sheng:data.data.sheng,
        code: data.data.code,
        place_desc: data.data.place_desc,
        introduce: data.data.introduce,
        urli:i,
        p_desc:data.data.p_desc,
        uid:data.data.uid,
        pid: data.data.pid,
        num: data.data.num,
        logistic_grade: data.data.logistic_grade,
        store_grade: data.data.store_grade,
        content: data.data.content,
        is_name: data.data.is_name,
        order_id: data.data.order_id,
        type_id:data.data.type_id,

        id: data.data.id,
        type: data.data.type,
        back_remark: data.data.back_remark,
        pro_id: data.data.pro_id,
        back: data.data.back,
        //退货
        addresses: data.data.addresses,
        telphone: data.data.telphone,
        names: data.data.names
      },
      //这里是上传图片时一起上传的数据
      success: (resp) => {
        console.log(resp)
        if(resp.errMsg=="uploadFile:ok"){
           success++;//图片上传成功，图片上传成功的变量+1
         }
      //这里可能有BUG，失败也会执行这里,所以这里应该是后台返回过来的状态码为成功时，这里的success才+1
      },
      fail: (res) => {
        fail++;//图片上传失败，图片上传失败的变量+1
        console.log('fail:' + i + "fail:" + fail);
        wx.showToast({
          title: '上传图网络异常！',
          duration: 2000
        });
      },
      complete: () => {
        console.log(i);
        i++;//这个图片执行完上传后，开始上传下一张
        if (i == data.path.length) {   //当图片传完时，停止调用          
          console.log('执行完毕');
          console.log('成功：' + success + " 失败：" + fail);
          if(success==4){
               setTimeout(function () {
                      console.log(that.globalData.froms)
                      if (that.globalData.froms=='user'){
                      wx.redirectTo({
                        url: '../user/user',
                      })
                    }else{
                      wx.switchTab({
                        url: '../company_user/company_user',
                      }) 
                    }
              }
                , 1000)
          }

        } else {//若图片还没有传完，则继续调用函数
          console.log(i);
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimg(data);
        }
      }
    });
  },
  globalData: {
    userId: ''
  },
  onLaunch: function () {
    var that=this
    // 获取小程序更新机制兼容
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager()
      updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
            console.log(res.hasUpdate);
        if (res.hasUpdate) {
          updateManager.onUpdateReady(function () {
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: function (res) {
                if (res.confirm) {
                  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                  updateManager.applyUpdate()
                }
              }
            })
          })
          updateManager.onUpdateFailed(function () {
            // 新的版本下载失败
            wx.showModal({
              title: '已经有新版本了哟~',
              content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
            })
          })
        }
      })
    } else {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }

    // this.position();
    this.getUserInfo();
  },

  getUserInfo: function (cb) {
    var that = this
    if (this.globalData.userInfo) {
      typeof cb == "function" && cb(this.globalData.userInfo)
    } else {
      //调用登录接口
      wx.login({
        success: function (res) {

          var code = res.code;
          wx.getUserInfo({
            success: function (res) {
               // console.log(res);
              that.globalData.userInfo = res.userInfo
              typeof cb == "function" && cb(that.globalData.userInfo);

              
              // wx.request({
              //   url: that.d.ceshiUrl + '/Api/User/login_one',
              //   method: 'post',
              //   data:{
              //     uid: that.globalData.userInfo['id'],
              //   },
              //   header: {
              //     'Content-Type': 'application/x-www-form-urlencoded'
              //   },
              //   success: function (res) {
              //   if(res.status==1){
              //     console("1123");
              //   }   
              //   },
              // });
              that.getUserSessionKey(code);
            }
          });
        }
      });
    }
  },
  getUserSessionKey: function (code) {
    //用户的订单状态
    var that = this;
    wx.request({
      url: that.d.ceshiUrl + '/Api/Login/getsessionkey',
      method: 'post',
      data: {
        code: code
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        //--init data    
        var data = res.data;
        if (data.status == 0) {
          wx.showToast({
            title: data.err,
            duration: 2000
          });
          return false;
        }
        that.globalData.userInfo['sessionId'] = data.session_key;
        that.globalData.userInfo['openid'] = data.openid;
        console.log(that.globalData.userInfo['openid'])
        if(typeof(that.globalData.userInfo['openid'])!='undefined'){
           wx.setStorageSync('openid', data.openid)
           that.onLoginUser();
        }
      },
      fail: function (e) {
        wx.showToast({
          title: 'session网络异常！err:getsessionkeys',
          duration: 2000
        });
      },
    });
  },
  onLoginUser: function () {
    var that = this;
    var user = that.globalData.userInfo;
     wx.setStorageSync('user', user);
    wx.request({
      url: that.d.ceshiUrl + '/Api/Login/authlogin',
      method: 'post',
      data: {
        SessionId: user.sessionId,
        gender: user.gender,
        NickName: user.nickName,
        HeadUrl: user.avatarUrl,
        openid: user.openid
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        //--init data        
        var data = res.data.arr;
        var status = res.data.status;
        if (status != 1) {
          wx.showToast({
            title: res.data.err,
            duration: 3000
          });
          return false;
        }
        that.globalData.userInfo['id'] = data.ID;
        that.globalData.userInfo['NickName'] = data.NickName;
        that.globalData.userInfo['HeadUrl'] = data.HeadUrl;
        var userId = data.ID;
        if (!userId) {
          wx.showToast({
            title: '登录失败！',
            duration: 3000
          });
          return false;
        }
        that.d.userId = userId;
        console.log(that.d.userId);
            wx.request({
                url: that.d.ceshiUrl + '/Api/index/store_user',
                method: 'post',
                data: {
                  store_id: that.d.store_Id,
                  user_id: that.d.userId,
                },
                header: {
                  'Content-Type': 'application/x-www-form-urlencoded'
                },
                success: function (res) {
                  var storedata=res.data
                  if(storedata.status){
                      that.d.store_Id = storedata.store_id;
                      that.d.store_sub_Id=storedata.store_id;
                  }
                },

            })
        //处理海报信息开始
                //获得二维码，头像存在本地
        wx.downloadFile({
            url: data.HeadUrl,
            success(res) {
              // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
              if (res.statusCode === 200) {
                      var tou=res.tempFilePath
                       wx.request({
                            url: that.d.ceshiUrl + '/Api/Bshare/index',
                            method: 'post',
                            data: {
                              uid: data.ID,
                              pid: 0,
                              store_id: 0,
                            },
                            header: {
                              'Content-Type': 'application/x-www-form-urlencoded'
                            },
                            success: function(res) {
                                var data1 = res.data;
                                wx.downloadFile({
                                url: data1.img,
                                success(res) {
                                  // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
                                  if (res.statusCode === 200) {

                                          var erweima=res.tempFilePath

                                       wx.request({
                                                url: that.d.ceshiUrl + '/Api/Poster/poster',
                                                data: {
                                                  uid:  data.ID,
                                                },
                                                method: 'post', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
                                                header: {
                                                  'Content-Type': 'application/x-www-form-urlencoded'
                                                },
                                                success: function (res) {
                                                  let rest = res.data;

                                                  if(rest.status==1){
                                                    // setTimeout(function() {
                                                      rest.data.tou=tou;
                                                      rest.data.erweima=erweima;
                                                      rest.data.nickname=data.NickName;
                                                      console.log(rest)
                                                      wx.setStorageSync("tempuser", rest.data)  
                                                    // }.bind(this), 1500)
                                                  } 
                                                }
                                        })
                        
                                  }
                                }
                             })
                            },
                            fail: function() {
                              wx.showToast({
                                title: '网络不给力！',
                                duration: 2000
                              });
                            }
                          });
              }
            }
         })
        //处理海报信息结束
        // 储存基本信息
        wx.setStorage({ key: "userInfo", data: data })
      },
      fail: function (e) {
        wx.showToast({
          title: 'loginuser网络异常！err:authlogin',
          duration: 2000
        });
      },
    });
  },
  getOrBindTelPhone: function (returnUrl) {
    var user = this.globalData.userInfo;
    if (!user.tel) {
      wx.navigateTo({
        url: 'pages/binding/binding'
      });
    }
  },
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
  },

  //第一种状态的底部  
  editTabBar: function () {
    var _curPageArr = getCurrentPages();
    var _curPage = _curPageArr[_curPageArr.length - 1];
    var _pagePath = _curPage.__route__;
    if (_pagePath.indexOf('/') != 0) {
      _pagePath = '/' + _pagePath;
    }
    var tabBar = this.globalData.tabBar;
    for (var i = 0; i < tabBar.list.length; i++) {
      tabBar.list[i].active = false;
      if (tabBar.list[i].pagePath == _pagePath) {
        tabBar.list[i].active = true;//根据页面地址设置当前页面状态    
      }
    }
    _curPage.setData({
      tabBar: tabBar
    });
  },
  //第二种状态的底部  
  editTabBar2:function () {
    var _curPageArr = getCurrentPages();
    var _curPage = _curPageArr[_curPageArr.length - 1];
    var _pagePath = _curPage.__route__;
    if (_pagePath.indexOf('/') != 0) {
      _pagePath = '/' + _pagePath;
    }
    var tabBar = this.globalData.tabBar2;
    for (var i = 0; i < tabBar.list.length; i++) {
      tabBar.list[i].active = false;
      if (tabBar.list[i].pagePath == _pagePath) {
        tabBar.list[i].active = true;//根据页面地址设置当前页面状态    
      }
    }
    _curPage.setData({
      tabBar: tabBar
    });
  },
  //第三种状态的底部  
  editTabBar3:function () {
    var _curPageArr = getCurrentPages();
    var _curPage = _curPageArr[_curPageArr.length - 1];
    var _pagePath = _curPage.__route__;
    if (_pagePath.indexOf('/') != 0) {
      _pagePath = '/' + _pagePath;
    }
    var tabBar = this.globalData.tabBar3;
    for (var i = 0; i < tabBar.list.length; i++) {
      tabBar.list[i].active = false;
      if (tabBar.list[i].pagePath == _pagePath) {
        tabBar.list[i].active = true;//根据页面地址设置当前页面状态    
      }
    }
    _curPage.setData({
      tabBar: tabBar
    });
  },
  globalData: {
    userInfo: null,
    latitude:0,
    longitude:0,
    imgs:'',
    froms:'',
    tabBar: {
      "color": "#858585",
      "selectedColor": "#e93d3b",
      "borderStyle": "whitesmoke",
      "backgroundColor": "#ffffff",
      "list": [
        {
          "pagePath": "/pages/index/index",
          "text": "首页",
          "iconPath": "https://tanghuzhao.cn/Public/images/icons/btn-tabs_01.png",
          "selectedIconPath": "https://tanghuzhao.cn/Public/images/icons/btn-tabs_07.png",
          "clas": "menu-item",
          active: true
        },
        {
          "pagePath": "/pages/step/index",
          "text": "步数",
          "iconPath": "https://tanghuzhao.cn/Public/images/icons/bushu.png",
          "selectedIconPath": "/images/bushus.png",
          "clas": "menu-item",
          active: false
        },
        {
          "pagePath": "/pages/charts/charts",
          "text": "排行榜",
          "iconPath": "https://tanghuzhao.cn/Public/images/icons/shangcheng.png",
          "selectedIconPath": "https://tanghuzhao.cn/Public/images/icons/shangcheng_s.png",
          "clas": "menu-item",
          active: false
        },
        {
          "pagePath": "/pages/my/my",
          "text": "我的",
          "iconPath": "https://tanghuzhao.cn/Public/images/icons/my.png",
          "selectedIconPath": "https://tanghuzhao.cn/Public/images/icons/my_s.png",
          "clas": "menu-item",
          active: false
        }
      ],
      "position": "bottom"
    },
    tabBar2: {
      "color": "#858585",
      "selectedColor": "#e93d3b",
      "borderStyle": "whitesmoke",
      "backgroundColor": "#ffffff",

      "list": [
        {
          "pagePath": "/pages/index/index",
          "text": "首页",
          "iconPath": "https://tanghuzhao.cn/Public/images/icons/btn-tabs_01.png",
          "selectedIconPath": "/images/shops.png",
          "clas": "menu-item2",
          active: true
        },
        {
          "pagePath": "/pages/category/index",
          "text": "分类",
          "iconPath": "https://tanghuzhao.cn/Public/images/icons/btn-tabs_03.png",
          "selectedIconPath": "/images/shopf.png",
          "clas": "menu-item2",
          active: false
        },
        {
          "pagePath": "/pages/cart/cart",
          "text": "购物车",
          "iconPath": "https://tanghuzhao.cn/Public/images/icons/btn-tabs_05.png",
          "selectedIconPath": "/images/shopg.png",
          "clas": "menu-item2",
          active: false
        },
        {
          "pagePath": "/pages/user/user",
          "text": "我的",
          "iconPath": "https://tanghuzhao.cn/Public/images/icons/btn-tabs_06.png",
          "selectedIconPath": "/images/shopw.png",
          "clas": "menu-item2",
          active: false
        }
      ],
      "position": "bottom"
    },
    tabBar3: {
      "color": "#858585",
      "selectedColor": "#e93d3b",
      "borderStyle": "whitesmoke",
      "backgroundColor": "#ffffff",

      "list": [
        {
          "pagePath": "/pages/purchase/index",
          "text": "首页",
          "iconPath": "https://tanghuzhao.cn/Public/images/icons/btn-tabs_01.png",
          "selectedIconPath": "/images/shops.png",
          "clas": "menu-item3",
          active: true
        },
        {
          "pagePath": "/pages/category/index1",
          "text": "分类",
          "iconPath": "https://tanghuzhao.cn/Public/images/icons/btn-tabs_03.png",
          "selectedIconPath": "/images/shopf.png",
          "clas": "menu-item3",
          active: false
        },
        {
          "pagePath": "/pages/member/index",
          "text": "我的",
          "iconPath": "https://tanghuzhao.cn/Public/images/icons/btn-tabs_06.png",
          "selectedIconPath": "/images/shopw.png",
          "clas": "menu-item3",
          active: false
        }
      ],
      "position": "bottom"
    },
  } 
});





